<template>
  <div class="seckill-goods">
    <a-card :bordered="false">
      <tablePage
        :columns="columns"
        :data-list="data"
        :enable-pagination="false"
      >
        <template #hours="{ data }">
          <a-tag v-for="item in data.hours" :key="item">{{
            `${item}:00`
          }}</a-tag>
        </template>
        <template #promotionStatuS="{ data }">
          <!-- START -->
          <span v-if="data.promotionStatus === 'NEW'">
            <a-badge status="success" style="margin-right: 10px" />新建</span
          >
          <span v-if="data.promotionStatus === 'success'">
            <a-badge status="danger" style="margin-right: 10px" />开始</span
          >
          <span v-if="data.promotionStatus === 'END'">
            <a-badge status="danger" style="margin-right: 10px" />结束</span
          >
          <span v-if="data.promotionStatus === 'CLOSE'">
            <a-badge status="danger" style="margin-right: 10px" />废弃</span
          >
        </template>
      </tablePage>
      <a-col :span="16">
        <a-space>
          <a-button
            v-if="promotionStatu === 'NEW'"
            type="outline"
            style="margin: 10px"
            @click="openSkuList"
            >选择商品</a-button
          >
        </a-space>
      </a-col>
      <a-tabs v-model="tabCurrent" type="card-gutter" @change="tabsChange">
        <a-tab-pane v-for="(tab, tabIndex) in goodsList" :key="tabIndex">
          <template #title
            ><icon-clock-circle /> {{ `${tab.hour}:00` }}</template
          >
          <a-table
            v-if="tabIndex == tabCurrent"
            v-model:selectedKeys="selectedKeys"
            :columns="goodsColumns"
            :data="tab.list"
            row-key="skuId"
            :pagination="false"
            :row-selection="rowSelection"
            @selection-change="changeSelect"
          >
            <template #originalPrice="{ record }"
              ><span>{{ unitPrice(record.originalPrice, '¥') }}</span></template
            >
            <template #quantity="{ record, rowIndex }">
              <a-input-number
                v-model="record.quantity" 
                :disabled="record.promotionApplyStatus === 'PASS'"
                @input="goodsList[tabIndex].list[rowIndex].quantity = record.quantity"
                :min="1"
              ></a-input-number>
            </template>
            <template #price="{ record, rowIndex }">
              <a-input-number
                v-model="record.price"
                :disabled="record.promotionApplyStatus === 'PASS'"
                @input="goodsList[tabIndex].list[rowIndex].price = record.price"
                :precision="2" :min="0.01"
              ></a-input-number>
            </template>
            <template #promotionApplyStatus="{ record }">
              <span>{{
                record.promotionApplyStatus === 'APPLY'
                  ? '申请'
                  : record.promotionApplyStatus === 'PASS'
                  ? '通过'
                  : record.promotionApplyStatus === 'REFUSE'
                  ? '拒绝'
                  : '未申请'
              }}</span>
            </template>
            <template #action="{ record, rowIndex }"
              ><a-button
                type="text"
                status="danger"
                @click="delGoods(record, rowIndex)"
                >删除</a-button
              ></template
            >
          </a-table>
        </a-tab-pane>
      </a-tabs>
      <a-col :span="16" :style="{ marginTop: '20px' }">
        <a-space>
          <a-button style="margin-right: 5px" @click="closeCurrentPage"
            >返回</a-button
          >
          <a-button v-if="promotionStatu === 'NEW'" type="primary" @click="save"
            >提交</a-button
          >
        </a-space>
      </a-col>
    </a-card>
    <skuselect
      v-if="isShowSkuselect"
      ref="skuSelect"
      :goods-or-sku="true"
      :api-params="apiParam"
      :default-goods-selected-list="goodsList[tabCurrent].list"
      @change="changSkuList"
    ></skuselect>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, reactive } from 'vue';
  import {
    seckillDetail,
    seckillGoodsList,
    delSeckillGoods,
    setSeckillGoods,
  } from '@/api/promotion';
  import tablePage from '@/components/table-pages/index.vue';
  import skuselect from '@/components/goods-sku-selector/index.vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ColumnsDataRule } from '@/types/global';
  import { unitPrice } from '@/utils/filters';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const route = useRoute();
  // 传递的参数
  const apiParam = {
    marketEnable: 'UPPER',
    authFlag: 'PASS',
    salesModel: 'RETAIL',
  };
  // 传递的参数
  const apiParams = {
    seckillId: route.query.id,
  };
  const skuSelect = ref(null) as any; // 商品选择器
  const data = ref<any>([]);
  const goodsList = ref<Array<any>>([]); // 商品列表
  const defaultGoodsList = ref([]); // 默认查询秒杀的商品
  const promotionStatu = ref<any>(); // 活动状态
  const tabCurrent = ref<any>(0);
  const tabIndex = ref<any>(0);
  const columns: ColumnsDataRule[] = [
    { title: '活动名称', dataIndex: 'promotionName', width: 200 },
    { title: '活动开始时间', dataIndex: 'startTime', width: 200 },
    { title: '报名截止时间', dataIndex: 'applyEndTime', width: 200 },
    {
      title: '时间场次',
      dataIndex: 'hours',
      slot: true,
      slotTemplate: 'hours',
      width: 500,
    },
    {
      title: '活动状态',
      dataIndex: 'promotionStatuS',
      slot: true,
      slotTemplate: 'promotionStatuS',
      width: 180,
    },
  ];
  const goodsColumns: any[] = [
    { title: '商品名称', dataIndex: 'goodsName' },
    {
      title: '商品价格',
      dataIndex: 'originalPrice',
      slotName: 'originalPrice',
    },
    { title: '库存', dataIndex: 'quantity', slotName: 'quantity' },
    { title: '活动价格', dataIndex: 'price', slotName: 'price' },
    {
      title: '状态',
      dataIndex: 'promotionApplyStatus',
      slotName: 'promotionApplyStatus',
    },
    { title: '操作', dataIndex: 'action', slotName: 'action' },
  ];
  const isShowSkuselect = ref(false);
  // 表格的行选择器配置
  const rowSelection = reactive<any>({
    type: 'checkbox',
    showCheckedAll: true,
    // selectedRowKeys: [],
    onlyCurrent: true,
  });
  const selectedKeys = ref([]);
  // 获取限时秒杀活动商品
  const getDataList = () => {
    // 处理过的时间 为‘1:00’
    const seckillHours = data.value[0].hours;
    seckillHours.forEach((e: any) => {
      goodsList.value.push({
        hour: e,
        list: [],
      });
    });
    seckillGoodsList({ seckillId: route.query.id }).then((res) => {
      if (res.data.result) {
        const data = res.data.result.records;
        seckillHours.forEach((e: any, index: number) => {
          data.forEach((i: any) => {
            if (i.timeLine == e) {
              goodsList.value[index].list.push(i);
            }
          });
        });
      }
    });
  };
  // 获取限时秒杀活动详情
  const getSeckillMsg = () => {
    seckillDetail(route.query.id).then((res) => {
      if (res.data.result) {
        data.value = [];
        data.value.push({
          ...res.data.result,
          hours: res.data.result.hours.split(','),
        });
        // 活动状态
        promotionStatu.value = res.data.result.promotionStatus;
        getDataList();
      }
    });
  };
  // 选择商品弹框
  const openSkuList = () => {
    isShowSkuselect.value = true;
    setTimeout(() => {
      skuSelect.value.modalData.visible = true;
    }, 10);
  };
  // 选择商品回调
  const changSkuList = (val: any) => {
    const list: any = [];
    val.forEach((e: any) => {
      list.push({
        settlementPrice: e.settlementPrice || 0,
        purchasePrice: 0,
        lowestPrice: e.lowestPrice || 0,
        highestPrice: e.highestPrice || 0,
        stock: e.stock || 0,
        goodsName: e.goodsName,
        price: e.price,
        originalPrice: e.price,
        promotionApplyStatus: e.promotionApplyStatus || '',
        quantity: e.quantity,
        seckillId: route.query.id,
        storeId: e.storeId,
        storeName: e.storeName,
        skuId: e.id,
        timeLine: data.value[0].hours[tabCurrent.value],
      });
    });
    goodsList.value[tabCurrent.value].list = list;
  };
  // 已选择的数据行发生改变时触发
  const changeSelect = () => {};
  // 当前标签值改变时触发
  const tabsChange = (value: any) => {
    tabCurrent.value = value;
  };
  // 删除
  const delGoods = (row: any, index: any) => {
    modal.confirm({
      title: '确认删除',
      content: '您确认要删除该商品吗?删除后不可恢复',
      alignCenter: false,
      onOk: async () => {
        if (row.promotionApplyStatus === 'PASS') {
          const params = {
            seckillId: row.seckillId,
            id: row.id,
          };
          const res = await delSeckillGoods(params);
          if (res.data.success) {
            goodsList.value[tabCurrent.value].list.splice(index, 1);
            Message.success('删除成功！');
          }
        } else {
          goodsList.value[tabCurrent.value].list.splice(index, 1);
          Message.success('删除成功！');
        }
      },
    });
  };
  // 关闭当前页面
  const closeCurrentPage = () => {
    router.go(-1);
  };
  // 提交秒杀商品
  const save = () => {
    const list = JSON.parse(JSON.stringify(goodsList.value));
    const params = {
      seckillId: route.query.id,
      applyVos: [],
    } as any;
    list.forEach((e: any) => {
      e.list.forEach((i: any) => {
        params.applyVos.push(i);
      });
    });
    setSeckillGoods(params).then((res) => {
      if (res.data.success) {
        Message.success('提交活动商品成功！');
        closeCurrentPage();
      }
    });
  };

  onMounted(() => {
    getSeckillMsg();
  });
</script>

<style lang="less" scoped>
  :deep(.arco-tag-size-medium) {
    margin-right: 10px;
  }

  .operation {
    margin: 10px 0;
  }

  .reason {
    cursor: pointer;
    color: #2d8cf0;
    font-size: 12px;
  }
</style>
